//
//  QYGRechargeDetailView.m
//  wawaji_ios
//
//  Created by 奇艺果 on 2017/12/26.
//  Copyright © 2017年 yiguo qi. All rights reserved.
//

#import "QYGRechargeDetailView.h"
#import "QYGRechargeDetailCell.h"
#import "QYGCoinRecordModel.h"
#import "QYGNetRequestModel.h"
#import "QYGPaymentModel.h"

static NSString *rechargeDetailID = @"rechargeDetailID";

@interface QYGRechargeDetailView()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *payBtn;
@property (nonatomic, assign) NSInteger currentPayId;
@property (strong, nonatomic) NSTimer *requestTimer;
@property (nonatomic, assign) NSInteger requestCount;

@property (nonatomic, strong) QYGCoinListModel *coinListModel;

@end

@implementation QYGRechargeDetailView


- (instancetype)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        [self viewWithcornerRadius:10 borderWidth:0 borderColor:nil backgroundColor:[UIColor colorWithHex:@"ffffff"]];
        [self setupUI];
    }
    return self;
}

#pragma mark - tableViewDelegate
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.coinListArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return ScaleH(66);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return  nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return  nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    QYGRechargeDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:rechargeDetailID forIndexPath:indexPath];
    cell.coinListModel = self.coinListArr[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    QYGRechargeDetailCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    self.coinListModel = self.coinListArr[indexPath.row];
    cell.selected = YES;
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    QYGRechargeDetailCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.selected = NO;
}
#pragma mark - setupUI
- (void)setupUI
{
    self.layer.cornerRadius = 10;
    self.layer.masksToBounds = YES;
    [self addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top);
        make.left.equalTo(self.mas_left);
        make.right.equalTo(self.mas_right);
        make.height.equalTo(@(ScaleW(55)));
    }];
    [self addSubview:self.payBtn];
    [self.payBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left).offset(ScaleW(15));
        make.right.equalTo(self.mas_right).offset(ScaleW(-15));
        make.bottom.equalTo(self.mas_bottom).offset(ScaleW(-15));
        make.height.equalTo(@(ScaleW(50)));
    }];
    [self addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).offset(ScaleW(3));
        make.left.equalTo(self.mas_left);
        make.right.equalTo(self.mas_right);
        make.bottom.equalTo(self.payBtn.mas_top).offset(ScaleW(-15));
    }];
}

#pragma mark - target
- (void)payBtnBtnClicked
{
    if(!self.coinListModel){
        [self makeToast:@"请选择充值金额"];
        return;
    }
    if( [SGUtil WXAppIsInstalled]){
        [self requestPay];
    }
}

#pragma mark - 内部方法
- (void)requestPay{
    
    self.userInteractionEnabled = NO;
    // 请求支付
    [SVProgressHUD show];
    QYGCoinListModel *coinListModel = self.coinListModel;
    //生成支付交易单号
    [QYGNetRequestModel postPaymentWithCoin_id:coinListModel.coinId completed:^(QYGPaymentModel *paymentModel) {
        // 获取支付参数配置
        self.currentPayId = paymentModel.pay_id;
        if(![QYGKeychain payType]){
            [QYGNetRequestModel getPayParamsWithPay_id:paymentModel.pay_id completed:^(QYGPreparamModel *prePaymentModel) {
                
                // 调微信支付
                [SGUtil shareUtil].coinListModel = coinListModel;
                [SGUtil shareUtil].pay_id = paymentModel.pay_id;
                [SGUtil WXPayWithOpenId:nil partnerId:prePaymentModel.partnerid prepayId:prePaymentModel.prepayid package:prePaymentModel.package nonceStr:prePaymentModel.noncestr stamp:prePaymentModel.timestamp sign:prePaymentModel.sign];
                self.userInteractionEnabled = YES;
            } WithErrorCodeBlock:^(NSError *error) {
                
                self.userInteractionEnabled = YES;
                [SVProgressHUD showWithStatus:@"稍后再试"];
            }];
        }else{
            self.requestTimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(requestAction) userInfo:nil repeats:YES];
        }
    } WithErrorCodeBlock:^(NSError *error) {
        self.userInteractionEnabled = YES;
        [SVProgressHUD showWithStatus:@"稍后再试"];
    }];
    
}
- (void)requestAction{
    self.requestCount += 1;
    [QYGNetRequestModel getCheckPaymentWithPay_id:self.currentPayId completed:^(QYGPaymentModel *paymentModel) {
        if( [paymentModel.status isEqualToString:@"paid"]){
            [self showPayResult:YES];
        }else{
            if(self.requestCount >5){
                // 支付失败
                [self showPayResult:NO];
            }
        }
    } WithErrorCodeBlock:^(NSError *error) {
        if(self.requestCount >5){
            // 支付失败
            [self showPayResult:NO];
        }
    }];
}

- (void)showPayResult:(BOOL)isSuccess{
    
    [SVProgressHUD dismiss];
    self.userInteractionEnabled = YES;
    [self.requestTimer invalidate];
    self.requestTimer = nil;
    self.requestCount = 0;
    if(self.rechargeCompletBlock){
        self.rechargeCompletBlock(isSuccess, self.coinListModel);
    }
}
- (void)setCoinListArr:(NSArray *)coinListArr{
    _coinListArr = coinListArr;
    [self.tableView reloadData];
}
#pragma mark lazy
- (UILabel *)titleLabel
{
    if(!_titleLabel)
    {
        _titleLabel = [SGUtil newLabelWithFont:ScaleFont(16) textColor:[UIColor colorWithHex:@"333333"] text:@"请选择充值金额"];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabel;
}

- (UITableView *)tableView
{
    if(!_tableView)
    {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[QYGRechargeDetailCell class] forCellReuseIdentifier:rechargeDetailID];
    }
    return _tableView;
}

- (UIButton *)payBtn
{
    if(!_payBtn)
    {
        _payBtn = [SGUtil newButtonWithTitleFont:ScaleFont(18) title:@"微信支付" titleColor:[UIColor colorWithHex:@"fefefe"]];
        [_payBtn addTarget:self action:@selector(payBtnBtnClicked) forControlEvents:UIControlEventTouchUpInside];
        [_payBtn viewWithcornerRadius:5 borderWidth:0 borderColor:nil backgroundColor:[UIColor colorWithHex:@"09bb07"]];
    }
    return _payBtn;
}

@end
